`
https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
`

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function (root) {
  const res = []
  if (root === null) return res

  const q = [root]

  // 控制方向，true时向右，false时向左
  let direction = true

  while (q.length) {
    const sz = q.length
    // 每到新的一层创建一个新列表
    // 把当前层的元素从左到右放进去
    res.push([])
    for (let i = 0; i < sz; i++) {
      const cur = q.shift()
      res[res.length - 1].push(cur.val)
      if (cur.left) q.push(cur.left)
      if (cur.right) q.push(cur.right)
    }
    // 本层遍历完后判断一下是否需要翻转
    if (!direction) res[res.length - 1].reverse()
    direction = !direction
  }

  return res
};